package com.jeecg.mvc.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;


public class ResourceLoader
{
	
	static Map<String,Map<String,String>> mapping =new HashMap<String,Map<String,String>>();
	
    public static void main(String[] args) throws IOException
    {
        ResourceLoader resourceLoader = new ResourceLoader();
        resourceLoader.loadStrutsFile();
    }

    public static void loadStrutsFile() throws IOException
    {
        InputStream input = null;
        try
        {
        	ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        	input = classloader.getResourceAsStream("struts.xml");
        	readxml(input);
        	
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    public static void readxml(InputStream input) throws JDOMException, IOException{
    	SAXBuilder sb = new SAXBuilder();
    	Document   document = sb.build(input);
    	 Element root = document.getRootElement(); 
    	  List<Element> list = root.getChildren();
    	  List<Element> formbeans =null;
    	  List<Element> actions = null; 
    	  for(Element e:list) {
    		  System.out.println("elementsName :"+e.getName());
    		   if(e.getName().equals("formbeans")){
    			   formbeans = e.getChildren("formbean");
    		   }
    		   if(e.getName().equals("actionmappings")){
    			   actions = e.getChildren("action");
    		   }
    	 }  
    	 for(Element formbean:formbeans){
   		   Map<String,String> map = new HashMap <String,String>();
   		   String formName = formbean.getAttribute("name").getValue();
   		   String formClass = formbean.getAttribute("form-class").getValue();
   		   String actionClass= getActionClassByFormName(actions,formName);
   		   map.put(formClass, actionClass);
   		   mapping.put(formName, map);   		   
   	   }   
    	  
    	  
    }
    
    
    public static String getActionClassByFormName(List<Element> actions,String formName){
    	for(Element action:actions){
 		   Attribute actionFormName = action.getAttribute("formname");
 		   if(actionFormName.getValue().equals(formName)){
 			  Attribute actionClass = action.getAttribute("action-class");
 			  return actionClass.getValue();
 			  
 		   }
 	   } 
    	
    	return "";
    }
    
    public Map<String,Map<String,String>> getMap(){
    	return mapping;
    }
    
    
}







